package com.wocai.jrt.orgadmin.stats.action;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.abel533.echarts.code.SeriesType;
import com.vteba.utils.common.ExportExcel;
import com.vteba.utils.date.DateUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductBean;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.stats.bean.OrgProductEmpStatsResBean;
import com.wocai.jrt.orgadmin.stats.bean.ProductEmpStatsReqBean;
import com.wocai.jrt.orgadmin.stats.bean.ProductEmpStatsResBean;
import com.wocai.jrt.orgadmin.stats.bean.ProductRecruitProgressResBean;
import com.wocai.jrt.orgadmin.stats.bean.ProductStatEleBean;
import com.wocai.jrt.orgadmin.stats.bean.ProductStatReqBean;
import com.wocai.jrt.orgadmin.stats.bean.ProductStatResBean;
import com.wocai.jrt.orgadmin.stats.service.spi.ProductStatsJobService;
import com.wocai.jrt.orgadmin.stats.service.spi.ProductStatsService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 图表-产品统计控制器
 * 
 * @author yinlei
 * @date 2015-8-7 9:24:38
 */
@Controller
@RequestMapping("/productStats")
public class ProductStatsAction extends GenericAction<Employee>{
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductStatsAction.class);
	private static final String PRODUCT_EMP_STAT_FILE_NAME = "产品销售报表";
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}
	
	@Inject
	private ProductStatsService productStatsServiceImpl; 
	@Inject
	private ProductService productServiceImpl;
	@Inject
	private ProductStatsJobService productStatsJobServiceImpl;
	
	@RequestMapping("/productStatsJob")
	public void productStatsJob() {
		productStatsJobServiceImpl.productStatsTask();
	}
	
	/**
	 * 跳转产品统计，初始化。
	 * 
	 * @param model
	 *            参数
	 * @return 员工List
	 */
	@RequestMapping("/getlist/{State}")
	public String getlist(@PathVariable("State") int State, Map<String, Object> maps) {
		try {
			List<ProductStatResBean> nameList = new ArrayList<ProductStatResBean>();
			if(3 == State){
				ProductBean product = new ProductBean();
				product.createCriteria().andOrgIdEqualTo(UserUtils.getOrgId()).andStateEqualTo(1).andAuditStateEqualTo(1);
				List<Product> list = productServiceImpl.queryForList(product);
				maps.put("size", list.size());
				maps.put("state", 3);
			}else if(1 == State){
				ProductBean product = new ProductBean();
				product.setOrderBy("create_time desc");
				product.createCriteria().andOrgIdEqualTo(UserUtils.getOrgId()).andStateNotEqualTo(0).andAuditStateEqualTo(1);
				List<Product> list = productServiceImpl.queryForList(product);
				int flag = 1;
				for(Product p:list){
					ProductStatResBean psr = new ProductStatResBean();
					if(flag <= 5){
						psr.setState(true);
						psr.setName(p.getBriefName());
						psr.setProductId(p.getId());
						nameList.add(psr);
						flag++;
					}else{
						psr.setState(false);
						psr.setName(p.getBriefName());
						psr.setProductId(p.getId());
						nameList.add(psr);
					}
				}
				maps.put("state", 1);
				maps.put("list", nameList);
			}else if(2 == State){
				ProductBean product = new ProductBean();
				product.createCriteria().andOrgIdEqualTo(UserUtils.getOrgId()).andAuditStateEqualTo(1);
				List<Product> list = productServiceImpl.queryForList(product);
				for(Product p:list){
					ProductStatResBean psr = new ProductStatResBean();
					psr.setName(p.getBriefName());
					psr.setProductId(p.getId());
					nameList.add(psr);
				}
				maps.put("list", nameList);
				maps.put("state", 2);
			}
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "stats/productStats/productChart";
	}
	
	/**
	 * 获取产品销售速率图表内容
	 * @param productStatReqBean
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/productSaleRate")
	public JsonBean productSaleRate(@RequestBody ProductStatReqBean productStatReqBean){
		JsonBean json = new JsonBean();
		//初始化 1.页面展示产品元素列表 2.产品名称列表 3.返回map
		List<String> displayList = productStatReqBean.getProductIdList();
		List<ProductStatEleBean> li = new ArrayList<ProductStatEleBean>();
		List<String> productNameList = new ArrayList<String>();
		Map<String,Object> map = new HashMap<String,Object>();
		
		if(10 < productStatReqBean.getProductIdList().size()){
			json.setCode(0);
			json.setMessage("对比产品不能超过10条");
			return json;
		}
		//初始化最大销售周期
		long maxSalesTerm = 0;
		
		//获取产品销售进度列表
		if(LOGGER.isInfoEnabled()){
			LOGGER.info("query param: [{}]",JSON.toJSONString(productStatReqBean));
		}
		List<ProductStatResBean> list = productStatsServiceImpl.getProductStatsResBeanList(UserUtils.getOrgId());
		//遍历产品销售进度列表
		for(String displayId:displayList){
			for(ProductStatResBean p:list){  
				//当产品id在需要展示的列表中时
				if(p.getProductId().equals(displayId)){
					//初始化页面展示元素
					ProductStatEleBean productStatEleBean = new ProductStatEleBean();
					List<Object> dataList = new ArrayList<Object>();
					//产品名称列表添加
					productNameList.add(p.getName());
					
					//最大销售周期计算
					if(maxSalesTerm < p.getSalesTerm()){
						maxSalesTerm = p.getSalesTerm();
					}
					
					//页面展示元素赋值
					productStatEleBean.setName(p.getName());
					productStatEleBean.setType(SeriesType.line);
					productStatEleBean.setSymbol(new String("none"));

					//数组转list
					Collections.addAll(dataList, p.getSalePercent());
					productStatEleBean.setData(dataList);
					productStatEleBean.setAmount(p.getAmount());
					productStatEleBean.setProductScale(p.getProductScale());
					//添加至页面展示列表
					li.add(productStatEleBean);
				}
			}
		}
		//封装数据
		map.put("list", li);
		map.put("maxSalesTerm", maxSalesTerm);
		map.put("productNameList", productNameList);
		json.setData(map);
		json.setCode(1);
		json.setMessage(SUCCESS);
		if(LOGGER.isInfoEnabled()){
			LOGGER.info("query success");
		}
		return json;
	}
	
	/**
	 * 获取产品募集进度
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/productRecruitProgress")
	public JsonBean productRecruitProgress(){
		JsonBean json = new JsonBean();
		//获取产品销售进度列表
		if(LOGGER.isInfoEnabled()){
			LOGGER.info("query param: [{}]",JSON.toJSONString(UserUtils.getOrgId()));
		}
		ProductRecruitProgressResBean prp = productStatsServiceImpl.getUncompletedProductRecruitProgressList(UserUtils.getOrgId());

		//封装数据
		json.setData(prp);
		json.setCode(1);
		json.setMessage(SUCCESS);
		if(LOGGER.isInfoEnabled()){
			LOGGER.info("query success");
		}
		return json;
	}
	
	/**
	 * 查询产品销售报表。
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/productEmpStats")
	public Map<String, Object> productEmpStats(@RequestBody ProductEmpStatsReqBean productEmpStatsReqBean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			//大于等于recordStart 小于recordEnd
			Integer recordStart = 0;
			Integer recordEnd = 10;
			if(productEmpStatsReqBean.getPage() == null){
				recordStart = 0;
				recordEnd = productEmpStatsReqBean.getPageSize();
			}else if(productEmpStatsReqBean.getPage() == 0){
				recordStart = 0;
				recordEnd = productEmpStatsReqBean.getPageSize();
			}else{
				recordStart = productEmpStatsReqBean.getPage();
				recordEnd = recordStart + productEmpStatsReqBean.getPageSize();
			}
			productEmpStatsReqBean.setOrgId(UserUtils.getOrgId());
			if(LOGGER.isInfoEnabled()){
				LOGGER.info("query param: [{}]",JSON.toJSONString(productEmpStatsReqBean));
			}
			OrgProductEmpStatsResBean eBean = productStatsServiceImpl.getOrgProductEmpStatsResBean(productEmpStatsReqBean);
			List<ProductEmpStatsResBean> list = eBean.getProductEmpStatsResBeanList();
			List<ProductEmpStatsResBean> showList = new ArrayList<ProductEmpStatsResBean>();
			List<String> productIdList = productEmpStatsReqBean.getProductIdList();
			//redis取出為空時，初始化一個對象扔給前台
			if(list == null){
				list = new ArrayList<ProductEmpStatsResBean>();
				result.put("iTotalRecords", 0); // 总记录数
				result.put("iTotalDisplayRecords", 0); // 显示的记录数
				result.put("aaData", list); // 返回的数据
			}else{
				if(productIdList.size() == 0){
					int end = recordEnd > list.size() ? list.size(): recordEnd;
					for(int i = recordStart;i < end;i++){
						showList.add(list.get(i));
					}
					result.put("aaData", showList); // 返回的数据
					result.put("iTotalRecords", list.size()); // 总记录数
					result.put("iTotalDisplayRecords", list.size()); // 显示的记录数
				}else if(productIdList.size() != 0){
					List<ProductEmpStatsResBean> li = new ArrayList<ProductEmpStatsResBean>();
					for(String productId:productIdList){
						for(ProductEmpStatsResBean pes:list){
							if(pes.getProductId().equals(productId)){
								li.add(pes);
							}
						}
					}
					int end = recordEnd > li.size() ? li.size(): recordEnd;
					for(int i = recordStart;i < end;i++){
						showList.add(li.get(i));
					}
					result.put("aaData", showList); // 返回的数据
					result.put("iTotalRecords", li.size()); // 总记录数
					result.put("iTotalDisplayRecords", li.size()); // 显示的记录数
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("get productEmpStats list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 查询产品销售报表。
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@RequestMapping("/productEmpStatsDownload")
	public String productEmpStatsDownload(ProductEmpStatsReqBean productEmpStatsReqBean, HttpServletResponse response) {
		try {
			productEmpStatsReqBean.setOrgId(UserUtils.getOrgId());
			OrgProductEmpStatsResBean eBean = productStatsServiceImpl.getOrgProductEmpStatsResBean(productEmpStatsReqBean);
			List<ProductEmpStatsResBean> list = eBean.getProductEmpStatsResBeanList();
			List<String> productIdList = productEmpStatsReqBean.getProductIdList();
			List<Object[]> exportList = new ArrayList<Object[]>();
			String[] columns = {"产品简称", "团队名称", "成交订单数", "销售额"};
			int[] columnWidths = {20, 20, 20, 30};
			//redis取出為空時，初始化一個對象扔給前台
			if(list == null){
				list = new ArrayList<ProductEmpStatsResBean>();
			} else {
				if (productIdList != null &&productIdList.size() != 0) {
					List<ProductEmpStatsResBean> li = new ArrayList<ProductEmpStatsResBean>();
					for (String productId:productIdList) {
						for (ProductEmpStatsResBean pes:list) {
							if (pes.getProductId().equals(productId)) {
								li.add(pes);
							}
						}
					}
					list = li;
				}
			}
			for (ProductEmpStatsResBean p:list ) {
				Object[] object = new Object[4];
//				object[0] = p.getProductId();
				object[0] = p.getBriefName();
				object[1] = p.getGroupName();
				object[2] = p.getTotalOrderNum();
				object[3] = p.getTotalSales();
				exportList.add(object);
			}
			ExportExcel exportExcel = new ExportExcel(columns, true, exportList);
			exportExcel.setColumnWidths(columnWidths);
			Workbook workbook = exportExcel.toExcel();
			
			String filename = PRODUCT_EMP_STAT_FILE_NAME + DateUtils.toDateString("yyyyMMddHHmmss") + ".xlsx";
			
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
			
			OutputStream out = response.getOutputStream();
			workbook.write(out);
			
			
			out.flush();
			out.close();
			workbook.close();
			response.flushBuffer();
		} catch (Exception e) {
			//e.printStackTrace();
			LOGGER.error("download file error, error=[{}]", e.getMessage());
		}
		return null;
	}
}
